package com.blb.service.impl;

import com.blb.mapper.BranchEnterpriseDao;
import com.blb.pojo.BranchCompany;
import com.blb.pojo.BranchEnterprise;
import com.blb.service.BranchEnterpriseService;
import com.blb.util.Page;
import com.blb.util.PageUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author 祖星毅
 */
@Service
public class BranchEnterpriseServiceImpl implements BranchEnterpriseService {
    @Autowired
    private BranchEnterpriseDao branchEnterpriseDao;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 分支公司动态表的分页查找
     * @param page
     * @param size
     * @return
     */
    @Override
    public Page selectByPage(Integer page, Integer size) {
        String key = "BranchPage"+page+""+size;
        ValueOperations<String, Page> operations = redisTemplate.opsForValue();
        //判断redis中是否有键为key的缓存
        Boolean hasKey = redisTemplate.hasKey(key);
        if (hasKey){
            System.out.println("缓存获取数据");
            return operations.get(key);
        }else {
            List<BranchEnterprise> branchEnterprises = branchEnterpriseDao.selectByPage((page - 1) * size, size);
            List<BranchEnterprise> branchEnterprises1 = branchEnterpriseDao.selectByPage(0, 0);
            Page page1 = PageUtil.page(branchEnterprises, branchEnterprises1,page,size);
            //写入缓存
            operations.set(key,page1,1, TimeUnit.MINUTES);
            return page1;
        }
    }


    /**
     * 分支公司动态表通过主键id查找
     * @param enterpriseId
     * @return
     */
    @Override
    public BranchEnterprise selectByPrimaryKey(Integer enterpriseId) {
        String key = "BranchEnter_"+enterpriseId;
        ValueOperations<String, BranchEnterprise> operations = redisTemplate.opsForValue();
        //判断redis中是否有键为key的缓存
        Boolean hasKey = redisTemplate.hasKey(key);
        if (hasKey){
            System.out.println("缓存获取数据");
            return operations.get(key);
        }else {
            BranchEnterprise branchEnterprise = branchEnterpriseDao.selectByPrimaryKey(enterpriseId);
            //写入缓存
            operations.set(key,branchEnterprise,1, TimeUnit.MINUTES);
            return branchEnterprise;
        }
    }
}
